package controller;

import jakarta.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pojo.SysUser;
import service.SysUserService;
import utils.Constants;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    private static final Logger logger = Logger.getLogger(LoginController.class);
    @Resource
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam("account")String account, @RequestParam("password")String password,
                          HttpServletRequest request, HttpSession session){
        SysUser sysUser=sysUserService.login(account,password);
        if(sysUser!=null){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "redirect:/sys/toMain";
        }else{
            request.setAttribute("error","用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping("/sys/toMain")
    public String toMain(){
        return "frame";
    }
}


